// Do not remove the include below
#include "Garduino.h"

unsigned long lastConnectionTime = 0; // last time we connected to Cosm
const unsigned long connectionInterval = 15000; // delay between connecting to Cosm in milliseconds
boolean lastConnected = false;

IPAddress ip(192, 168, 1, 40);
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(216,52,233,122);      // numeric IP for api.pachube.com
char server[] = "api.pachube.com"; // name address for pachube API

char buffer[80]; // the code uses 70 characters.

int resetCounter = 0;

void resetEthernetShield() {
	Serial.println("Resetting Ethernet Shield.");
	Serial.println();

	client.stop();
	delay(1000);
	Serial.print("Connected: ");
	if (Ethernet.begin(mac) == 0) {
		Serial.println(
				"failed to get an IP address using DHCP, trying manually");
		Ethernet.begin(mac, ip);
	}
	Serial.println("OK");
	delay(1000);
}

long getLength(double value) {
	long a;
	int digits = 1;

	a = (long) value * 1000;

	if (a < 0) {
		a = abs(a);
		digits++;
	}
	// continually divide the value by ten,
	// adding one to the digit count for each
	// time you divide, until you're at 0:
	int dividend = a / 10;

	while (dividend > 0) {
		dividend = dividend / 10;
		digits++;
	}

	if ((value < 1) && (value > 0)) {
		digits = 4;
	} else if ((value > -1) && (value < 0)) {
		digits = 5;
	}
	return digits + 1;
}

// send the supplied value to Cosm, printing some debug information as we go
void sendData(temperature sensorsV) {

	int messageLength = 0;

	// if there's a successful connection:
	if (client.connect(server, 80)) {
		Serial.println("connecting...");
		// send the HTTP PUT request:
		client.print("PUT /v2/feeds/");
		client.print(FEED_ID);
		client.println(".csv HTTP/1.1");
		client.println("Host: api.pachube.com");
		client.print("X-PachubeApiKey: ");
		client.println(API_KEY);
		client.print("User-Agent: ");
		client.println(USERAGENT);
		client.print("Content-Length: ");
		messageLength = getLength(sensorsV.humidity) + getLength(sensorsV.temp)
				+ getLength(sensorsV.dewPointD)
				+ getLength(sensorsV.soilHumidity)
				+ getLength(sensorsV.thermistor)
				+ getLength(sensorsV.photocell);
		Serial.print("Longitud => ");
		Serial.println(messageLength);
		//Serial.println(getLength(sensorsV.humidity));
		//Serial.println(getLength(sensorsV.temp));
		//Serial.println(getLength(sensorsV.dewPointD));
		//Serial.println(getLength(sensorsV.soilHumidity));
		//Serial.println(getLength(sensorsV.thermistor));
		//Serial.println(getLength(sensorsV.photocell));
		client.println(messageLength + 74);

		// last pieces of the HTTP PUT request:
		client.println("Content-Type: text/csv");
		client.println("Connection: close");
		client.println();

		// here's the actual content of the PUT request:
		client.print("humidity,");
		client.println((float) sensorsV.humidity, 3);
		client.print("temperature,");
		client.println((float) sensorsV.temp, 3);
		client.print("dewPoint,");
		client.println((float) sensorsV.dewPointD, 3);
		client.print("soilHumidity,");
		client.println((float) sensorsV.soilHumidity, 3);
		client.print("thermistor,");
		client.println((float) sensorsV.thermistor, 3);
		client.print("photocell,");
		client.println((float) sensorsV.photocell, 3);

		Serial.print("Fecha,");
		Serial.println(buffer);
		Serial.print("humidity,");
		Serial.println((float) sensorsV.humidity, 3);
		Serial.print("temperature,");
		Serial.println((float) sensorsV.temp, 3);
		Serial.print("dewPoint,");
		Serial.println((float) sensorsV.dewPointD, 3);
		Serial.print("soilHumidity,");
		Serial.println((float) sensorsV.soilHumidity, 3);
		Serial.print("thermistor,");
		Serial.println((float) sensorsV.thermistor, 3);
		Serial.print("photocell,");
		Serial.println((float) sensorsV.photocell, 3);
		resetCounter = 0;
	} else {
		Serial.println("Connection Failed.");
		Serial.println();

		resetCounter++;

		if (resetCounter >= 5) {
			resetEthernetShield();
		}

		lastConnectionTime = millis();
	}
	lastConnectionTime = millis();
}

//The setup function is called once at startup of the sketch
void setup() {
	Serial.begin(9600);
	// Add your initialization code here
	// start the Ethernet connection and the server:
	Serial.print("Connected: ");
	if (Ethernet.begin(mac) == 0) {
		Serial.println(
				"failed to get an IP address using DHCP, trying manually");
		Ethernet.begin(mac, ip);
	}
	Serial.println("OK");

	pinMode(SOIL_PIN, INPUT);
	pinMode(THER_PIN, INPUT);
	pinMode(PHOTO_PIN, INPUT);
	pinMode(WATER_PIN, INPUT);

	// Start by clearing the Write Protect bit
	// Otherwise the clock data cannot be written
	// The whole register is written,
	// but the WP-bit is the only bit in that register.
	ds1302.DS1302_write(DS1302_ENABLE, 0);

	// Disable Trickle Charger.
	//ds1302.DS1302_write (DS1302_TRICKLE, 0x00);

	// Remove the next define,
	// after the right date and time are set.
	//#define SET_DATE_TIME_JUST_ONCE
#ifdef SET_DATE_TIME_JUST_ONCE
	// Set a time and date
	// This also clears the CH (Clock Halt) bit,
	// to start the clock.
	ds1302_struct rtc;
	// Fill the structure with zeros to make
	// any unused bits zero
	memset ((char *) &rtc, 0, sizeof(rtc));

	rtc.Seconds = 0;
	rtc.Seconds10 = 0;
	rtc.CH = 0;// 1 for Clock Halt, 0 to run;
	rtc.Minutes = 7;
	rtc.Minutes10 = 0;
	rtc.h24.Hour = 2;
	rtc.h24.Hour10 = 2;
	rtc.h24.hour_12_24 = 0;// 0 for 24 hour format
	rtc.Date = 1;
	rtc.Date10 = 3;
	rtc.Month = 3;
	rtc.Month10 = 0;
	rtc.Day = 1;
	rtc.Year = 3;
	rtc.Year10 = 1;
	rtc.WP = 0;

	// Write all clock data at once (burst mode).
	ds1302.DS1302_clock_burst_write( (uint8_t *) &rtc);
#endif
}

// The loop function is called in an endless loop
void loop() {
	ds1302_struct rtc;

	char data[80];
	String sbuffer;
	int water;

	// if there's incoming data from the net connection.
	// send it out the serial port.  This is for debugging
	// purposes only:
	if (client.available()) {
		char c = client.read();
		//Serial.print(c);
	}

	// if there's no net connection, but there was one last time
	// through the loop, then stop the client:
	if (!client.connected() && lastConnected) {
		//	Serial.println();
		//	Serial.println("disconnecting.");
		client.stop();
	}
	//sensors.readSoil();
	// Read all clock data at once (burst mode).
	ds1302.DS1302_clock_burst_read((uint8_t *) &rtc);

	sprintf(buffer, "%02d:%02d:%02d %02d/%02d/%d, \t",
			(rtc.h24.Hour10 * 10) + rtc.h24.Hour,
			(rtc.Minutes10 * 10) + rtc.Minutes,
			(rtc.Seconds10 * 10) + rtc.Seconds, (rtc.Date10 * 10) + rtc.Date,
			(rtc.Month10 * 10) + rtc.Month,
			2000 + (rtc.Year10 * 10) + rtc.Year);

	// READ DATA
	int chk = sensors.readAll();
	//int chk=sensors.read();

	if (!client.connected()
			&& (millis() - lastConnectionTime > connectionInterval)) {
		switch (chk) {
		case DHTLIB_OK:
			if (sensors.thermistor >= 9) {
				pinMode(WATER_PIN, OUTPUT);
				digitalWrite(WATER_PIN, HIGH);
				water = 1;
				//delay(100);
				//pinMode(WATER_PIN,INPUT);
			} else {
				pinMode(WATER_PIN, OUTPUT);
				digitalWrite(WATER_PIN, LOW);
				water = 0;
				pinMode(WATER_PIN, INPUT);
			}

			sendData(sensors);

			// store the state of the connection for next time through
			// the loop:
			lastConnected = client.connected();
			break;
		case DHTLIB_ERROR_CHECKSUM:
			Serial.print("Checksum error,\t");
			break;
		case DHTLIB_ERROR_TIMEOUT:
			Serial.print("Time out error,\t");
			break;
		default:
			Serial.print("Unknown error,\t");
			break;
		}
	}
}

